package com.example.module_home.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.lib_common.user.UserUtils
import com.example.lib_mvicore.ui.BaseMVIFragment
import com.example.lib_widget.redpacket.RedPacketEnum
import com.example.lib_widget.redpacket.RedPacketEvent
import com.example.module_home.databinding.FragmentHomeBinding
import com.example.module_home.databinding.FragmentSimpleTypeBinding
import com.example.module_home.intent.SimpleVideoIntent
import com.example.module_home.model.entity.SimpleVideoEntity
import com.example.module_home.state.SimpleVideoState
import com.example.module_home.ui.adapter.SimpleRecyclerviewAdapter
import com.example.module_home.viewmodel.SimpleVideoViewModel
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus

/**
 * @author yaotianxue
 * @description
 * @date 2024/10/28
 */
class SimpleTypeFragment:BaseMVIFragment() {
    private lateinit var mBinding: FragmentSimpleTypeBinding
    private lateinit var mSimpleVideoViewModel: SimpleVideoViewModel
    var page: Int = 0
    val pagesize: Int = 10
    var channelId: String = ""

    var adapter: SimpleRecyclerviewAdapter? = null
    override fun generateViewModel() {
        mSimpleVideoViewModel = ViewModelProvider(requireActivity())[SimpleVideoViewModel::class.java]
    }

    override fun initView() {
        super.initView()
        adapter = SimpleRecyclerviewAdapter(object :SimpleRecyclerviewAdapter.SubscibeOnClickListener{
            override fun onClick(position: Int, entity: SimpleVideoEntity) {

            }

        },object :SimpleRecyclerviewAdapter.SharedOnClickListener{
            override fun onClick(position: Int, entity: SimpleVideoEntity) {

            }

        },object :SimpleRecyclerviewAdapter.PlayOnClickListener{
            override fun onClick(entity: SimpleVideoEntity) {

            }

        }, onPreload = {
            page ++
            getSimpleVideoData()
            showMsg("预加载下一页数据")
        }, preloadItemCount = 3)

        val layoutManager = LinearLayoutManager(requireContext())
        layoutManager.orientation = RecyclerView.VERTICAL
        mBinding?.rvFragmentSimple?.layoutManager = layoutManager
        mBinding?.rvFragmentSimple?.adapter = adapter
        mBinding?.rvFragmentSimple?.setHasFixedSize(true) //优化：固定高，减少测量册书
        mBinding?.rvFragmentSimple?.setItemViewCacheSize(3)
        mBinding?.rvFragmentSimple?.setRecycledViewPool(RecyclerView.RecycledViewPool())


    }

    override fun initData() {
        super.initData()
        channelId = arguments?.get("channelid").toString()
        getSimpleVideoData()
    }

    private fun getSimpleVideoData(){
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                mSimpleVideoViewModel.intents.send(SimpleVideoIntent.getSimpleVideo(channelId,page,pagesize))
            }
        }
    }
    private var isStart = false //动画是否启动

    /**
     * 红包动画
     */
    private fun startPlayAnim() {
        if(!UserUtils.isLogin()){
           return
        }
        if(isStart){
            EventBus.getDefault().post(RedPacketEvent(RedPacketEnum.RESUME))
        }else{
            EventBus.getDefault().post(RedPacketEvent(RedPacketEnum.INIT))
            isStart = true
        }

    }

    override fun initEvent() {
        //滑动监听
        mBinding.rvFragmentSimple.addOnScrollListener(object : RecyclerView.OnScrollListener(){
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                when(newState){
                    RecyclerView.SCROLL_STATE_IDLE->{ //停止滚动
                        Glide.with(requireActivity()).resumeRequests()
                        EventBus.getDefault().post(RedPacketEvent(RedPacketEnum.PAUSE)) //暂停
                    }
                    RecyclerView.SCROLL_STATE_DRAGGING->{ //滚动
                        Glide.with(requireActivity()).pauseRequests()
                        startPlayAnim() //启动
                    }
                    RecyclerView.SCROLL_STATE_SETTLING->{//滚动
                        Glide.with(requireActivity()).pauseRequests()
                        startPlayAnim() //启动
                    }
                }
            }
        })

    }



    override fun lazyLoad() {

    }

    override fun getFragmentRootView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        mBinding =   FragmentSimpleTypeBinding.inflate(inflater,container,false)
        return mBinding.root
    }

    override fun handleState() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                mSimpleVideoViewModel.state.collect{
                    when(it){
                        is SimpleVideoState.SimpleVideosSuccess->{ //列表中
                            adapter?.addData(it.list.toMutableList())


                        }
                        is SimpleVideoState.RecommendSimpleVideosSuccess->{

                        }
                        is SimpleVideoState.Failed->{

                        }
                        is SimpleVideoState.RecommendFailed->{

                        }
                        is SimpleVideoState.Init->{

                        }
                        is SimpleVideoState.Empty->{

                        }
                    }
                }
            }
        }
    }
}